package StudyCode.summary.csv;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class WriteCSVFile {

	public static void main(String[] args) {
		List<List<String>> lists = new ArrayList<>();
		ArrayList<String> strings = new ArrayList<>();
		strings.add("www");
		strings.add("tah1986");
		strings.add("com");
		lists.add(strings);
		write(lists, "E:/Copy/1.csv", "utf-8");
	}

	public static void write(List<List<String>> list, String fileName,
	                         String charsetName) {
		File outFile = new File(fileName);

		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;

		try {
			fos = new FileOutputStream(outFile);
			osw = new OutputStreamWriter(fos, charsetName);
			bw = new BufferedWriter(osw);
			for (int j = 0; j < list.size(); j++) {
				List<String> rowList = list.get(j);
				for (int i = 0; i < rowList.size(); i++) {
					String str = rowList.get(i);
					bw.write("\"");
					bw.write(str);
					bw.write("\"");

					if (i < rowList.size() - 1) {
						bw.write(",");
					}
				}
				if (j < list.size() - 1) {
					bw.write("\n");
				}
			}
			bw.flush();
			System.out.println("CSV 文件 " + fileName + " 写入成功");
			System.out.println(String.format("%s 行", list.size()));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (IOException e) {
			}
			try {
				osw.close();
			} catch (IOException e) {
			}
			try {
				bw.close();
			} catch (IOException e) {
			}
		}
	}
}
